import cgi
import os
from google.appengine.ext.webapp import template

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db


book_name = ""
cmd = ""
temp_xml_output = ""

class Greeting(db.Model):
  author = db.UserProperty()
  book_name = db.StringProperty()
  content = db.TextProperty()
  #content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)


class MainPage(webapp.RequestHandler):
  def get(self):
    global book_name
    login_user = users.get_current_user()
    #book_name = self.request.get('book_name', 'root')

    if globals().has_key( 'book_name' ) == False:
		book_name = 'root'
    if book_name is '':
		book_name = 'root'
    greetings_query = Greeting.all().order('-date')
    greetings_query.filter("author =", users.get_current_user())
    greetings_query.filter("book_name =", book_name)

    greetings = greetings_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
	  'login_user': login_user,
	  'book_name': book_name,
      'greetings': greetings,
      'url': url,
      'url_linktext': url_linktext,
      }

    #self.response.headers.add_header("STYLESHEET","text/css","codebase/dhtmlxtree.css")
    self.response.headers['Pragma'] = "no-cache" 
    self.response.headers['Expires'] = "Sat, 26 Jul 1997 05:00:00 GMT" 
#<meta http-equiv="cache-control" content="no-cache"> 
#<meta http-equiv="pragma" content="no-cache"> 
#<meta http-equiv="expires" content="-1"> 
	
    #self.response.headers.add_header('script','src="codebase/dhtmlxcommon.js"')
    #self.response.headers.add_header('script','src="codebase/dhtmlxtree.js"')
    #self.response.headers.add_header('script','src="codebase/dhtmlxtree_start.js"')

    path = os.path.join(os.path.dirname(__file__), 'templete/dhtml_tree.html')
    #path = os.path.join(os.path.dirname(__file__), 'templete/web_tree.html')
    #path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class MainPage2(webapp.RequestHandler):
  def get(self):
    self.response.out.write('<html><body>')

    greetings = db.GqlQuery("SELECT * FROM Greeting WHERE content=:q2 ORDER BY date DESC LIMIT 10")
    #greetings = db.GqlQuery("SELECT * FROM Greeting ORDER BY date DESC LIMIT 10")
    greetings.filter("author =", users.get_current_user())

    for greeting in greetings:
      if greeting.author:
        self.response.out.write('<b>%s</b> wrote:' % greeting.author.nickname())
      else:
        self.response.out.write('An anonymous person wrote:')
      self.response.out.write('<blockquote>%s</blockquote>' %
                              cgi.escape(greeting.content))

    # Write the submission form and the footer of the page
    self.response.out.write("""
          <form action="/memory/sign" method="post">
            <div><textarea name="content" rows="3" cols="60"></textarea></div>
            <div><input type="submit" value="Sign Guestbook"></div>
          </form>
        </body>
      </html>""")

class XmlOutput(webapp.RequestHandler):
  def get(self):
    global book_name
    global cmd
    global temp_xml_output

    #print cmd
    if cmd == 'add book name':
        cmd = ''
        self.response.headers['Content-Type'] = 'text/xml'
        str = "<?xml version='1.0' encoding='utf-8'?>\n<tree id='0'>\n"
        str += temp_xml_output
        str += "</tree>\n"
    else:
        #select data from db.
        greetings_query = Greeting.all().order('-date')
        greetings_query.filter("author =", users.get_current_user())
        greetings_query.filter("book_name =", book_name)
        greetings = greetings_query.fetch(1)
        #next two condition is must:
        # 1 Content-Type is text/xml
        # 2 <?xml ver ...   before not space.
        self.response.headers['Content-Type'] = 'text/xml'
        str = "<?xml version='1.0' encoding='utf-8'?>\n<tree id='0'>\n"
        if greetings :
		    str += greetings[0].content
        else :
		    str += ""
        str += "</tree>\n"
    self.response.out.write( str )

class Guestbook(webapp.RequestHandler):
  def post(self):
    global book_name
    global cmd
    global temp_xml_output
	#select data from db.
    cmd = self.request.get('cmd')
    book_name = self.request.get('book_name','root')
    if cmd == 'change book name':
	    cmd = ''
    elif cmd == 'add book name':
        add_book_name = self.request.get('add_book_name','')
        #print 'add_book_name = ', add_book_name
        #cmd = ''
        greetings_query = Greeting.all().order('-date')
        greetings_query.filter("author =", users.get_current_user())
        greetings_query.filter("book_name =", add_book_name)
        greetings = greetings_query.fetch(1)
        temp_xml_output = ''
        if greetings :
            #print 'find db'
            greeting = greetings[0]
            temp_xml_output = greeting.content
        #print 'temp_xml_output1 = ', temp_xml_output
        temp = self.request.get( 'content' )
        temp_xml_output += temp
        #temp_xml_output = temp.replace('id=\'', 'id=\'q_')
        #print 'temp_xml_output2 = ', temp_xml_output
    else:
        greetings_query = Greeting.all().order('-date')
        greetings_query.filter("author =", users.get_current_user())
        greetings_query.filter("book_name =", book_name)
        greetings = greetings_query.fetch(1)
        if greetings :
		    greeting = greetings[0]
        else :
		    greeting = Greeting()
		    greeting.book_name = book_name
        if users.get_current_user():
          greeting.author = users.get_current_user()
        greeting.content = self.request.get('content')
        greeting.put()
    self.redirect('/memory/memroy')

application = webapp.WSGIApplication([
	('/memory/xml', XmlOutput)
	,('/memory/sign', Guestbook)
	,('/memory/.*', MainPage)
	],debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

#{% for greeting in greetings %}
#//tree.loadXMLString( "{{ greeting.content }}" )
#{% endfor %}
#dev_appserver.py --clear_datastore echostock/
#{% for greeting in greetings %}
#{{ greeting.content }}
#{% endfor %}
	#<input id="content" name="content" rows="3" type=text cols="60">
		#Book Name : <input id="book_name" name="book_name" type="text" value="{{ book_name }}" size=20 onkeypress="if(event.keyCode==13){}">




	#<br>
    #<a href="{{ url }}">{{ url_linktext }}</a><br>
    #User Name : {{ login_user }}<br>
	#<form name='output_xml' action="/memory/sign" method="post">
		#Book Name : <input id="book_name" name="book_name" type="text" value="{{ book_name|escape }}" size=20 >
		#<br>
		#<textarea id="content" name="content" rows="5" cols="60"></textarea>
	#</form>
    #<br>

#<link rel="STYLESHEET" type="text/css" href="codebase/dhtmlxtree.css">
#<script  src="codebase/dhtmlxcommon.js"></script>
#<script  src="codebase/dhtmlxtree.js"></script>
	#<a href="javascript:void(0);" onClick="alert( tree.getAllSubItems(tree.getSelectedItemId(),true) ) ;">Show item</a><br>
	#<a href="javascript:void(0);" onClick="alert( tree.getAllSubItems(0,true) ) ;">Show item all</a><br>
	#<a href="javascript:void(0);" onClick="alert( tree.getSelectedItemId() ) ;">Show select item</a><br>
	#<a href="javascript:void(0);" onClick="alert( tree.getLevel(tree.getSelectedItemId()) ) ;">Show select level</a><br>
	#<a href="javascript:void(0);" onClick="alert( tree.getXml(tree.getSelectedItemId()) ) ;">test xml</a><br>
    #{% for greeting in greetings %}
      #{% if greeting.author %}
        #<b>{{ greeting.author.nickname }}</b> wrote:
      #{% else %}
       #An wakuwaku person wrote:
      #{% endif %}
      #<blockquote>{{ greeting.book_name|escape }}</blockquote>
      #<blockquote>{{ greeting.content|escape }}</blockquote>
    #{% endfor %}
